'use strict'
import { App, ScrollView, View, Button } from '../../component'
import style from './css.css'
import Canvas from './canvas'
import Videos from './video'
import ControlBox from './control'
import Play from './play'
import Record from './record'
import Intro from './intro'
import Chat from './Chat'
import Result from './result'
import OnLine from './onLine'
import NoMoney from './noMoney'
import { observer, inject } from 'mobx-react'
import { Int64BE } from 'int64-buffer'
import msgpack from 'msgpack-lite'
import ws from '../../config/ws'
import getData from '../../config/getData'
const heartbeatTime = 25 * 1000
const tabid = 0

@inject('room', 'user') @observer class Live extends React.Component {
  static propTypes = {
    match: PropTypes.any,
    history: PropTypes.object,
    room: PropTypes.object,
    user: PropTypes.object
  }
  state = { hide: true }
  _hanleGameBtnStart = this._hanleGameBtnStart.bind(this)
  _hanleGameBtnEnd = this._hanleGameBtnEnd.bind(this)
  _reStartGame = this._reStartGame.bind(this)
  _onopen = this._onopen.bind(this)
  _error = this._error.bind(this)
  _closeWs = this._closeWs.bind(this)
  _onmessage = this._onmessage.bind(this)
  _startGame = this._startGame.bind(this)
  _controlVideo = this._controlVideo.bind(this)
  _overGame = this._overGame.bind(this)
  _TXSDK = null
  controlTimeFlag = null
  roundId = null
  isOver = true
  videos = []
  gameTime = 0
  scrollView = null
  constructor (props) {
    super(props)
    ws.onopen = this._onopen
    ws.onmessage = this._onmessage
    ws.error = this.error
    ws.onclose = this.closeWs
  }
  componentDidMount () {
    const { anchorID, roomID } = this.props.match.params
    this.props.room.getRoomMsg(anchorID, roomID, () => {
      const urlDate = {
        ver: '7.0.0',
        source: this.props.room.userInfo.source,
        source_id: this.props.room.userInfo.source_id,
        room_id: roomID,
        tabid,
        app: 2066
      }
      ws.init('wss://mangowss.app-remix.com/access', urlDate)
      // setTimeout(() => { this.props.room.changeRoomState(-1) }, 2000)
    })
  }
  componentWillUnmount () {
    ws.instance.close()
    this.props.room.clearVideos()
  }
  // 手按着，操作开始
  _hanleGameBtnStart (i) {
    if (ws.instance === null || this.isOver) { return }
    let flag = 0
    if (this.props.room.canvasPos === 0) {
      if (i === 0) { flag = 7 } // 左
      if (i === 1) { flag = 3 } // 右
      if (i === 2) { flag = 1 } // 上
      if (i === 3) { flag = 5 } // 下
    }
    else {
      if (i === 0) { flag = 5 }
      if (i === 1) { flag = 1 }
      if (i === 2) { flag = 7 }
      if (i === 3) { flag = 3 }
    }
    if (i === 4) {
      flag = 9
      window.doll.stopLoop()
    }

    const data = getData(flag, this.props.room.userInfo, this.roundId, tabid)
    ws.instance.send(data)
    if (this.controlTimeFlag == null && i < 4) { this.controlTimeFlag = setInterval(() => { ws.instance.send(data) }, 200) }
  }
  // 手放开，操作结束
  _hanleGameBtnEnd (i) {
    if (ws.instance === null || this.isOver) { return }
    let flag = 0
    if (this.currentVideo === 0) {
      if (i === 0) { flag = 8 }
      if (i === 1) { flag = 4 }
      if (i === 2) { flag = 2 }
      if (i === 3) { flag = 6 }
    }
    else {
      if (i === 0) { flag = 6 }
      if (i === 1) { flag = 2 }
      if (i === 2) { flag = 8 }
      if (i === 3) { flag = 4 }
    }
    const data = getData(flag, this.props.room.userInfo, this.roundId)
    ws.instance.send(data)
    if (this.controlTimeFlag) {
      clearInterval(this.controlTimeFlag)
      this.controlTimeFlag = null
    }
  }
  // 开始游戏
  _startGame () {
    if (ws.instance) {
      const ts = new Date().getTime()
      const data = {
        i: Int64BE(this.props.room.userInfo.source_id),
        b: Int64BE(0),
        d: 0,
        p: 86,
        z: 66,
        o: this.props.room.userInfo.source,
        t: Int64BE(ts),
        m: { o: 1 }
      }
      const buffer = msgpack.encode(data)
      ws.instance.send(buffer)
    }
  }
  _reStartGame () {
    this.isOver = true
    this.props.room.changeGameState(0)
    this._startGame()
  }
  // WS 链接上
  _onopen (e) {
    this.heartbeat = setInterval(() => {
      const ts = new Date().getTime()
      // 发送心跳信息
      const data = {
        i: Int64BE(this.props.room.userInfo.source_id),
        d: 0,
        p: 10,
        z: 66,
        o: this.props.room.userInfo.source,
        t: Int64BE(ts),
        m: ''
      }
      const buffer = msgpack.encode(data)
      ws.instance.send(buffer)
    }, heartbeatTime)
  }
  // 控制video 播放 ／ 暂停
  _controlVideo (flag) {
    if (!this.videos) { return }
    if (flag) {
      this.videos[0].play()
      this.videos[1].play()
    }
    else {
      this.videos[0].pause()
      this.videos[1].pause()
    }
  }
  // 成功上机
  _successStartGame (roundId, time) {
    if (this._TXSDK && this.isOver) {
      this._TXSDK()
      this._controlVideo(false)
      this.roundId = roundId
      this.isOver = false
      this.props.room.changeGameState(0, time)
    }
  }
  // 结束游戏
  _overGame () {
    if (this.props.room.gameState !== -1) {
      this.isOver = true
      this.props.room.changeGameState(-1)
      TXWawaVideo.destroy()
      TXWawaVideo._isStart = false
      this._controlVideo(true)
    }
  }
  // WS 接收到信息
  _onmessage (data) {
    console.log(data)
    const { changeInRoomNumber, addChat, changenoMoneyState, changeGameState } = this.props.room
    // 修改人数
    if (data.u !== 0) { changeInRoomNumber(data.u) }
    // xxx 来到
    if (data.p === 4) { addChat(`${data.m.u.n} ${data.m.m}`) }
    // 文案
    if (data.p === 24) { if (data.m.c) { addChat(data.m.c) } }
    // 上机成功
    if (data.p === 86 && data.m.o === 2) { this._successStartGame(data.m.i, data.m.l) }
    // 游戏结果，但是并不是结束
    if (data.p === 86 && data.m.o === 5) {
      console.log('游戏结果')
      // 抓到
      if (data.m.r === 1) { this.props.room.changeRoomState(1) }
      // 没抓到
      else if (data.m.r === 2) { this.props.room.changeRoomState(-1) }
    }
    // 余额
    if (data.p === 14) {
      this.props.room.changeCoin(data.m.d)
      this.props.user.changeBalance(data.m.d)
    }
    if (data.p === 87) {
      // 有人在玩
      if (data.m.o === 3) {
        const { n, a, s, d, l, i } = data.m
        const id = d.toString()
        const source = s
        if (id === this.props.room.userInfo.source_id && source === this.props.room.userInfo.source) { this._successStartGame(i, l) }
        else {
          console.log('别人玩')
          const user = { avatar: a, name: n }
          this.props.room.changePlayerMsg(user)
        }
      }
      // 空闲
      if (data.m.o === 6) { this._overGame() }
      // 维护中
      if (data.m.o === 7) { changeGameState(-3) }
    }
    // 不够钱
    if (data.p === 9 && data.m.e === -2) { changenoMoneyState() }
    if (data.p === 9) {
      changeGameState(-1)
      addChat(data.m.m)
    }
  }
  // WS 错误
  _error (e) { clearInterval(this.heartbeat) }
  _closeWs (e) {
    console.log(e)
    this.props.room.addChat('网络不好，重连中....')
  }
  // 加载完后渲染
  _renderByLoadOver () {
    const { playerMsg, videos, changeGameState, dollMusic, changeVideoPos, dollImage, videosPos, dollDetail, coin, txDetail, gameState, canvasPos } = this.props.room
    if (videos.length > 0) {
      return (
        <View className={style.livePlay}>
          <Videos
            videos={videos.slice()}
            dollImage={dollImage}
            dollMusic = {dollMusic}
            videosPos={videosPos}
            changeVideoPos = {changeVideoPos}
            getRef = {(res) => { this.videos = res }}
          />
          <Canvas
            getTXSDK={(res) => { this._TXSDK = res }}
            txDetail={txDetail}
            state={gameState}
            changeGameState = { changeGameState }
            videosPos={canvasPos}
          />
          <Chat chatList={ this.props.room.chatList } scrollView={this.scrollView} />
          <OnLine number={this.props.room.inRoomNumber } />
          <Button
            tapClassName={style.controlCameraPress}
            className={style.controlCamera}
            tap={() => { changeVideoPos(this.videos) }}>
          </Button>
          <Play
            state = {gameState}
            hanleGameBtnStart={this._hanleGameBtnStart}
            hanleGameBtnEnd={this._hanleGameBtnEnd}
          />
          <ControlBox
            tap={this._startGame}
            dollDetail={dollDetail}
            coin={coin}
            state = {gameState}
            history={this.props.history}
            playerMsg={ playerMsg }
          />
        </View>
      )
    }
  }
  render () {
    return (
      <App noSysScroll={true}>
        <ScrollView className={style.liveBox} getIScroll={(res) => { this.scrollView = res }}>
          <View className={style.livePlayBox}>
            {this._renderByLoadOver()}
          </View>
          <Record recordList={ this.props.room.recordList } />
          <Intro
            images={this.props.room.dollDetail.doll_design_pics}
            label={ this.props.room.dollDetail.doll_specs_pic}
          />
        </ScrollView>
        <Result tap={this._reStartGame} overGame={this._overGame} share={() => { this.setState({ hide: false }) }} />
        <NoMoney changenoMoneyState={ this.props.room.changenoMoneyState } resultState={this.props.room.noMoneyState} history={ this.props.history } />
        <View className={ this.state.hide ? style.hide : style.shareBox } tap={() => { this.setState({ hide: true }) }} >
          <View className={ style.share }></View>
        </View>
      </App>
    )
  }
}

export default Live
